package it.trekker.upload;

import it.trekker.converter.IJsonConverter;
import it.trekker.converter.JsonConverter;
import it.trekker.db.Excursion;
import it.trekker.db.ExcursionCoordinate;
import it.trekker.db.ExcursionCoordinateDAO;
import it.trekker.db.ExcursionDAO;
import it.trekker.db.Poi;
import it.trekker.db.PoiDAO;
import it.trekker.upload.json.ExcursionAdapter;
import it.trekker.upload.xml.IXmlExporter;
import it.trekker.upload.xml.XmlExporterFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

public abstract class UploadHelper {

	protected static final String TAG = UploadHelper.class.getSimpleName();

	protected static final String STORAGE_DIR = "Trekker";
	protected static final String PREFIX = "trekker_export_";
	protected static final String JSON_EXTENSION = ".json";
	protected static final String XML_EXTENSION = ".xml";

	protected File exportFile;
	protected FileOutputStream fOut;
	//	protected BufferedOutputStream bos; TODO

	protected IJsonConverter jsonConverter;
	protected ExcursionDAO excursionDAO;
	protected ExcursionCoordinateDAO excursionCoordDAO;
	protected PoiDAO poiDAO;
	
	
	
	public UploadHelper(Context ctx) {
		jsonConverter = new JsonConverter();
		excursionDAO = new ExcursionDAO(ctx);
		excursionCoordDAO = new ExcursionCoordinateDAO(ctx);
		poiDAO = new PoiDAO(ctx);
	}

	public String export2JsonFile(User user) throws IOException {

		// Open file
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String filePath = PREFIX + timeStamp + JSON_EXTENSION;
		openFile(filePath);

		// Open DAO
		excursionDAO.open();
		excursionCoordDAO.open();
		poiDAO.open();

		// Load data
		List<Excursion> excursionsList = excursionDAO.getAllExcursions();
		ExcursionAdapter[] excursionAdapterArray = new ExcursionAdapter[excursionsList.size()];
		for(int i = 0 ; i < excursionsList.size() ; i++ ) {
			excursionAdapterArray[i] = new ExcursionAdapter();
			excursionAdapterArray[i].setUser(user);
			excursionAdapterArray[i].setExcursion(excursionsList.get(i));
			excursionAdapterArray[i].setCoordinates(
					excursionCoordDAO.getAllCoordinatesByExcursion(
							excursionsList.get(i).getId()
							)
					);
			excursionAdapterArray[i].setPois(
					poiDAO.getAllPoisByExcursion(
							excursionsList.get(i).getId()
							)
					);
		}

		// Close DAO
		poiDAO.close();
		excursionCoordDAO.close();
		excursionDAO.close();

		// Write and close file
		String json = jsonConverter.Excursion2UploadArray2Json(excursionAdapterArray);
		fOut.write(json.getBytes());
		//		bos.write(json.getBytes()); TODO
		closeFile();
		
		return exportFile.getAbsolutePath();
	}


	public void export2XmlFile() throws IOException {

		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		openFile(PREFIX + timeStamp + XML_EXTENSION);

		// Open DAO
		excursionDAO.open();
		excursionCoordDAO.open();
		poiDAO.open();

		IXmlExporter xmlExporter = new XmlExporterFile(fOut);

		xmlExporter.startDocumentXml();
		xmlExporter.openExcursionsXml();

		List<Excursion> excursionsList = excursionDAO.getAllExcursions();
		for(Excursion exc : excursionsList) {
			List<ExcursionCoordinate> coordinatesList = excursionCoordDAO.getAllCoordinatesByExcursion(exc.getId());
			List<Poi> poisList = poiDAO.getAllPoisByExcursion(exc.getId());

			xmlExporter.openExcursionXml(exc);

			xmlExporter.openExcursionCoordinatesXml();
			for(ExcursionCoordinate coord : coordinatesList) {
				xmlExporter.openExcursionCoordinateXml(coord);
				xmlExporter.closeExcursionCoordinateXml();
			}
			xmlExporter.closeExcursionCoordinatesXml();

			xmlExporter.openPoisXml();
			for(Poi poi : poisList) {
				xmlExporter.openPoiXml(poi);
				xmlExporter.closePoiXml();
			}
			xmlExporter.closePoisXml();

			xmlExporter.closeExcursionXml();
		}

		xmlExporter.closeExcursionsXml();
		xmlExporter.endDocumentXml();

		//		IXmlExporter xmlExporter = new XmlExporter();
		//		
		//		bos.write(xmlConverter.startDocumentXml().getBytes());
		//		bos.write(xmlConverter.openExcursionsXml().getBytes());
		//		
		//		List<Excursion> excursionsList = excursionDAO.getAllExcursions();
		//		for(Excursion exc : excursionsList) {
		//			List<ExcursionCoordinate> coordinatesList = excursionCoordDAO.getAllCoordinatesByExcursion(exc.getId());
		//			List<Poi> poisList = poiDAO.getAllPoisByExcursion(exc.getId());
		//			
		//			bos.write(xmlConverter.openExcursionXml(exc).getBytes());
		//			
		//			bos.write(xmlConverter.openExcursionCoordinatesXml().getBytes());
		//			for(ExcursionCoordinate coord : coordinatesList) {
		//				bos.write(xmlConverter.openExcursionCoordinateXml(coord).getBytes());
		//				bos.write(xmlConverter.closeExcursionCoordinateXml().getBytes());
		//			}
		//			bos.write(xmlConverter.closeExcursionCoordinatesXml().getBytes());
		//			
		//			bos.write(xmlConverter.openPoisXml().getBytes());
		//			for(Poi poi : poisList) {
		//				bos.write(xmlConverter.openPoiXml(poi).getBytes());
		//				bos.write(xmlConverter.closePoiXml().getBytes());
		//			}
		//			bos.write(xmlConverter.closePoisXml().getBytes());
		//			
		//			bos.write(xmlConverter.closeExcursionXml().getBytes());
		//		}
		//		
		//		bos.write(xmlConverter.closeExcursionsXml().getBytes());
		//		bos.write(xmlConverter.endDocumentXml().getBytes());


		// Close DAO
		poiDAO.close();
		excursionCoordDAO.close();
		excursionDAO.close();

		closeFile();

	}
	

	public void openFile(String fileName) throws IOException {
		// To be safe, you should check that the SDCard is mounted
		// using Environment.getExternalStorageState() before doing this.

		String storageState = Environment.getExternalStorageState();

		if(storageState.equals(Environment.MEDIA_MOUNTED) && !storageState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			//					File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), STORAGE_DIR);
			File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), STORAGE_DIR);
			// This location works best if you want the created images to be shared
			// between applications and persist after your app has been uninstalled.

			// Create the storage directory if it does not exist
			if (! mediaStorageDir.exists()) {
				if (! mediaStorageDir.mkdirs()) {
					Log.d(TAG, "failed to create directory");
					return;
				}
			}

			// Create a file name
			exportFile = new File(mediaStorageDir.getPath() + File.separator + fileName);
			exportFile.createNewFile();

			fOut =  new FileOutputStream(exportFile);
			//bos = new BufferedOutputStream(fOut); TODO
		}
	}

	
	public void closeFile() throws IOException {
		//		bos.close(); TODO
		fOut.close();
	}


	public abstract boolean uploadFile(String filePath, String serverUrl);
	
}
